package com.lifeng.controller;

import com.lifeng.bean.MsgBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * Created by lifeng on 2019/5/27.
 */
@Controller
public class WsController {
    private static final Logger log = LoggerFactory.getLogger(WsController.class);
    @Resource
    private SimpMessagingTemplate messagingTemplate;

    /**点对点发送*/
    @MessageMapping("/chat")
    public void handleChat(@RequestBody MsgBean msgBean) {
        //通过SimpMessagingTemplate的convertAndSendToUser向用户发送消息。
        //第一参数表示接收信息的用户，第二个是浏览器订阅的地址，第三个是消息本身
        messagingTemplate.convertAndSendToUser(msgBean.getReceiveid(), "/queue/chat",msgBean.getSenderid()+"-发送----->"+msgBean.getMsg());
    }

    /**SendTo广播发送*/
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(String msg) {
        System.out.println("收到客户端消息:"+msg);
        messagingTemplate.convertAndSend("/topic/hello","服务端收到:"+msg);
        return "发送成功";
    }
}
